<template>
  <AModalPro
    v-bind="$attrs"
    title="编辑用户"
    :open="props.open"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="onOk"
    @cancel="handleCancel"
    @close="props.onCancel"
  >
    <ASpin :spinning="spinning">
      <UserEditFrom
        ref="formRef"
        v-model:value="formState"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        :rules="userRules"
      >
      </UserEditFrom>
    </ASpin>
  </AModalPro>
</template>

<script setup>
import { ref, toValue, watch } from 'vue';
import { AModalPro } from '@/components/iteration';
import { useState, useFetch } from '@/hooks';
import { fetchGetUser } from '@/api/system/user';
import { userRules } from '@/constants/rules';
import { UserEditFrom } from '../modules';

defineOptions({
  inheritAttrs: false // 禁用透传
});

const props = defineProps({
  open: { type: Boolean, default: false },
  userId: String,
  onFinish: Function,
  onCancel: Function
});

const initValues = {
  userName: '',
  nickName: '',
  phoneNumber: '',
  email: '',
  status: 0,
  remark: ''
};
const formRef = ref(null);
const [formState, setFormState] = useState(initValues);
const [loading, setLoading] = useState(false);
const { spinning, onFetch } = useFetch(fetchGetUser, false);

watch(
  () => props.open,
  (val) => val && onFetch(props.userId).then(setFormState)
);

const handleCancel = () => {
  props.onCancel?.();
  setTimeout(() => {
    setFormState(initValues);
    toValue(formRef)?.resetFields();
  }, 200);
};

const onOk = async () => {
  try {
    setLoading(true);
    await toValue(formRef)
      .callback.validate()
      .then((res) => props.onFinish?.({ ...res, userId: props.userId }));
    toValue(formRef).resetFields();
  } catch (e) {
    await Promise.reject(e);
  } finally {
    setLoading(false);
  }
};
</script>

<style lang="scss" scoped></style>
